package com.example.jiagoujiexiang.interceptor;

import com.example.jiagoujiexiang.Service.impl.userServiceimpl;
import com.example.jiagoujiexiang.Utils.Constant;
import com.example.jiagoujiexiang.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.ui.Model;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Component
public class AdminInterceptor implements HandlerInterceptor {
    @Autowired
    userServiceimpl userService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();

        User user = userService.getUserByName((String) session.getAttribute(Constant.LOGIN_USER));

        // 检查用户是否已登录并且是管理员
        if (user != null && "admin".equals(user.getUsername())) {
            return true; // 允许访问
        } else {
            response.sendRedirect("/login"); // 重定向到登录页面
            return false; // 拒绝访问
        }
    }

}
